<script setup lang="ts">
import { computed, reactive, ref, watchEffect } from 'vue';
import { useRouter } from 'vue-router';

import { useUserStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { updateProfileApi, uploadAvatarApi } from '#/api/core/auth';

defineOptions({ name: 'AccountProfile' });

interface AvatarOption {
  id: string;
  src: string;
}

const router = useRouter();
const userStore = useUserStore();

const defaultAvatar = userStore.userInfo?.avatar || '/images/Avatar.png';

const defaultAvatarOption: AvatarOption = {
  id: 'default-avatar',
  src: defaultAvatar,
};

const avatarOptions = ref<AvatarOption[]>([defaultAvatarOption]);

const activeAvatarId = ref<string>(defaultAvatarOption.id);
const activeAvatarUrl = ref<string>(defaultAvatarOption.src);
const uploading = ref(false);
const submitting = ref(false);
const isSuccess = ref(false);

const form = reactive({
  username: '',
  gender: '保密',
  mobile: '',
  email: '',
  companyName: '',
  creditCode: '',
});

watchEffect(() => {
  const info = userStore.userInfo;
  if (!info) {
    return;
  }
  form.username = info.realName || info.username || '';
  form.gender = info.sex || '保密';
  form.mobile = info.phone || '';
  form.email = info.email || '';
  form.companyName = (info as any)?.companyName || '';
  form.creditCode = (info as any)?.creditCode || '';

  const avatar = info.avatar || activeAvatarUrl.value;
  if (avatar) {
    activeAvatarUrl.value = avatar;
    const existed = avatarOptions.value.find((item) => item.src === avatar);
    if (existed) {
      activeAvatarId.value = existed.id;
    } else {
      avatarOptions.value.unshift({
        id: `avatar-${Date.now()}`,
        src: avatar,
      });
      activeAvatarId.value = avatarOptions.value[0]?.id ?? activeAvatarId.value;
    }
  }
});

const genderOptions = [
  { label: '男', value: '男' },
  { label: '女', value: '女' },
  { label: '保密', value: '保密' },
];

const uploadInputRef = ref<HTMLInputElement | null>(null);

function handleSelectAvatar(option: AvatarOption) {
  activeAvatarId.value = option.id;
  activeAvatarUrl.value = option.src;
}

function triggerUpload() {
  uploadInputRef.value?.click();
}

function extractUploadUrl(response: any): string {
  const payload =
    response?.result ?? response?.data?.result ?? response?.data ?? response;
  if (typeof payload === 'string') {
    return payload;
  }
  if (payload?.url) {
    return payload.url as string;
  }
  if (payload?.message && typeof payload.message === 'string') {
    return payload.message;
  }
  if (payload?.fullPath) {
    return payload.fullPath as string;
  }
  return '';
}

async function handleUpload(event: Event) {
  const file = (event.target as HTMLInputElement)?.files?.[0];
  if (!file) {
    return;
  }
  uploading.value = true;
  try {
    const response = await uploadAvatarApi(file);
    const url = extractUploadUrl(response);
    if (!url) {
      throw new Error('未获取到文件地址');
    }
    const id = `${Date.now()}`;
    avatarOptions.value.push({
      id,
      src: url,
    });
    activeAvatarId.value = id;
    activeAvatarUrl.value = url;
    message.success('头像上传成功');
  } catch (error: any) {
    console.error('上传头像失败:', error);
    message.error(
      error?.response?.data?.message ||
        error?.message ||
        '上传失败，请稍后重试',
    );
  } finally {
    uploading.value = false;
    if (uploadInputRef.value) {
      uploadInputRef.value.value = '';
    }
  }
}

const isSubmitDisabled = computed(
  () =>
    !form.username ||
    !form.companyName ||
    !form.creditCode ||
    !form.email ||
    submitting.value,
);

async function handleSubmit() {
  if (isSubmitDisabled.value) {
    message.warning('请完整填写必填信息后再保存');
    return;
  }
  submitting.value = true;
  try {
    await updateProfileApi({
      email: form.email,
      companyName: form.companyName,
      creditCode: form.creditCode,
      sex: form.gender,
      avator: activeAvatarUrl.value,
    });
    message.success('账户信息修改完成');
    isSuccess.value = true;
  } catch (error: any) {
    console.error('更新资料失败:', error);
    message.error(
      error?.response?.data?.message ||
        error?.message ||
        '更新资料失败，请稍后重试',
    );
  } finally {
    submitting.value = false;
  }
}

function handleCancel() {
  router.back();
}

function goHome() {
  router.push('/visitor-management');
}
</script>

<template>
  <div class="min-h-[calc(100vh-120px)] bg-[#f7f3ee] py-10">
    <div
      class="mx-auto w-full max-w-4xl rounded-2xl border border-[#f0d7b2] bg-white p-10 shadow-[0_12px_40px_rgba(237,200,162,0.3)]"
    >
      <template v-if="isSuccess">
        <h1 class="mb-14 text-2xl font-semibold text-[#5d412b]">账户管理</h1>
        <div class="flex flex-col items-center justify-center space-y-6 py-16">
          <div
            class="flex h-20 w-20 items-center justify-center rounded-full bg-[#e6f7e7]"
          >
            <span class="text-4xl">✔️</span>
          </div>
          <div class="text-center">
            <h2 class="text-xl font-semibold text-[#5d412b]">
              账户信息修改完成
            </h2>
            <p class="mt-2 text-sm text-[#8c8885]">账户信息修改完成</p>
          </div>
          <button
            type="button"
            class="rounded-full bg-[#d6a15f] px-10 py-3 text-sm font-medium text-white transition-colors hover:bg-[#c9904b]"
            @click="goHome"
          >
            返回首页
          </button>
        </div>
      </template>
      <template v-else>
        <h1 class="mb-8 text-2xl font-semibold text-[#5d412b]">账户管理</h1>

        <div
          class="flex flex-col space-y-10 lg:flex-row lg:space-x-10 lg:space-y-0"
        >
          <div class="flex flex-col items-center space-y-6 lg:w-1/3">
            <div class="relative h-32 w-32">
              <img
                :src="activeAvatarUrl"
                alt="当前头像"
                class="h-full w-full rounded-full border-4 border-[#f2c998] object-cover shadow-lg"
              />
              <span
                class="absolute bottom-0 right-2 rounded-full bg-white px-3 py-1 text-xs text-[#a87c4f] shadow"
              >
                编辑
              </span>
            </div>

            <div class="flex items-center space-x-3">
              <button
                v-for="option in avatarOptions"
                :key="option.id"
                class="relative h-16 w-16 overflow-hidden rounded-full border-2"
                :class="[
                  option.id === activeAvatarId
                    ? 'border-[#f2c998] shadow-[0_0_12px_rgba(242,201,152,0.55)]'
                    : 'border-transparent opacity-70 hover:opacity-100',
                ]"
                type="button"
                @click="handleSelectAvatar(option)"
              >
                <img
                  :src="option.src"
                  alt="头像选项"
                  class="h-full w-full object-cover"
                />
              </button>
              <button
                class="flex h-16 w-16 items-center justify-center rounded-full border-2 border-dashed border-[#d6b184] text-[#d6b184] transition-colors hover:border-[#c49966] hover:text-[#c49966]"
                type="button"
                :disabled="uploading"
                @click="triggerUpload"
              >
                {{ uploading ? '上传中' : '+' }}
              </button>
              <input
                ref="uploadInputRef"
                type="file"
                accept="image/*"
                class="hidden"
                @change="handleUpload"
              />
            </div>
          </div>

          <div class="flex-1 space-y-6">
            <div class="grid gap-6 md:grid-cols-2">
              <label class="flex flex-col space-y-2">
                <span class="text-sm text-[#a87c4f]">用户名</span>
                <input
                  v-model="form.username"
                  type="text"
                  disabled
                  placeholder="用户名"
                  class="rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
                />
              </label>

              <label class="flex flex-col space-y-2">
                <span class="text-sm text-[#a87c4f]">性别</span>
                <select
                  v-model="form.gender"
                  class="rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
                >
                  <option
                    v-for="option in genderOptions"
                    :key="option.value"
                    :value="option.value"
                  >
                    {{ option.label }}
                  </option>
                </select>
              </label>

              <label class="flex flex-col space-y-2">
                <span class="text-sm text-[#a87c4f]">手机号</span>
                <input
                  v-model="form.mobile"
                  type="tel"
                  placeholder="手机号"
                  class="rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
                />
              </label>

              <label class="flex flex-col space-y-2">
                <span class="text-sm text-[#a87c4f]">邮箱</span>
                <input
                  v-model="form.email"
                  type="email"
                  placeholder="邮箱"
                  class="rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
                />
              </label>

              <label class="flex flex-col space-y-2 md:col-span-2">
                <span
                  class="flex items-center justify-between text-sm text-[#a87c4f]"
                >
                  <span>公司名称</span>
                  <!-- <span class="text-xs text-[#ef6c57]">*修改后需客服审核</span> -->
                </span>
                <input
                  v-model="form.companyName"
                  type="text"
                  placeholder="输入公司名称"
                  class="rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
                />
              </label>

              <label class="flex flex-col space-y-2 md:col-span-2">
                <span
                  class="flex items-center justify-between text-sm text-[#a87c4f]"
                >
                  <span>公司统一社会信用代码</span>
                  <!-- <span class="text-xs text-[#ef6c57]">*修改后需客服审核</span> -->
                </span>
                <input
                  v-model="form.creditCode"
                  type="text"
                  placeholder="公司统一社会信用代码"
                  class="rounded-lg border border-[#f2c998] px-4 py-3 text-sm text-[#5d412b] placeholder-[#d1b494] focus:border-[#d6b184] focus:outline-none focus:ring-2 focus:ring-[#f8dfc3]"
                />
              </label>
            </div>
          </div>
        </div>

        <div class="mt-12 flex justify-end space-x-4">
          <button
            type="button"
            class="rounded-full bg-[#d6d1cd] px-8 py-3 text-sm font-medium text-[#6f6c69] transition-colors hover:bg-[#c7c1bc]"
            @click="handleCancel"
          >
            取消
          </button>
          <button
            type="button"
            class="rounded-full bg-[#d6a15f] px-8 py-3 text-sm font-medium text-white transition-colors hover:bg-[#c9904b] disabled:cursor-not-allowed disabled:bg-[#e3c4a0]"
            :disabled="isSubmitDisabled"
            @click="handleSubmit"
          >
            {{ submitting ? '提交中...' : '保存资料' }}
          </button>
        </div>
      </template>
    </div>
  </div>
</template>
